package top.chmin.project.cloud.common;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import top.chmin.project.cloud.sys.user.UserColumn;

import java.util.List;
import java.util.stream.Stream;

/**
 * chmin
 * 2024/1/11 10:16
 * cloud-code
 */
@Slf4j
public class SelectHandler {
    private final Condition condition;

    public SelectHandler(Condition condition) {
        this.condition = condition;
    }

    public void autoSelect(Class<?> resultClass) {
        new UserColumn();
        List<Column> columnList = ModelColumn.modelColumnMap.get(condition.modelClass);
        log.debug("columnList: {}", JSONUtil.toJsonStr(columnList));
        if (condition.modelClass.equals(resultClass)) {
            log.debug("返回标准对象");
            condition.selectList = columnList.stream()
                    .map(c -> c.columnName.equals(c.fieldName) ? c.columnName : c.columnName + " AS " + c.fieldName)
                    .toList();
        } else {
            log.debug("返回扩展对象");
            Stream.of(resultClass.getDeclaredFields()).forEach(f -> {
                log.debug("fieldName: {}", f.getName());
                if (f.isAnnotationPresent(BindColumn.class)) {
                    log.debug("使用BindColumn扩展");
                    BindColumn bindColumn = f.getAnnotation(BindColumn.class);
                    columnList.stream()
                            .filter(c -> c.columnName.equals(bindColumn.value()))
                            .findFirst()
                            .ifPresent(c -> {
                                String expression = bindColumn.expression();
                                String columnName = expression.replace("#c#", c.columnName);
                                condition.selectList.add(columnName.equals(c.fieldName) ? columnName : columnName + " AS " + f.getName());
                            });
                } else {
                    log.debug("查找同名字段: {}", f.getName());
                    columnList.stream()
                            .filter(c -> c.fieldName.equals(f.getName()))
                            .findFirst()
                            .ifPresent(c -> condition.selectList.add(c.columnName.equals(c.fieldName) ? c.columnName : c.columnName + " AS " + c.fieldName));
                }
            });
        }
        log.debug("selectList: {}", condition.selectList);
    }
}
